package com.itheima.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dto.LoginDTO;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.service.EmpService;
import com.itheima.vo.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;

    @Override
    public PageBean<Emp> findByPage(Integer page, Integer pageSize, String name, Integer gender, LocalDate begin, LocalDate end) {
        //1. 开启分页
        PageHelper.startPage(page, pageSize);

        //2.执行查询
        Page<Emp> p = (Page<Emp>) empMapper.findList3(name, gender, begin, end);

        //3. 组装返回数据
        return new PageBean<Emp>(p.getTotal(), p.getResult());
    }

    @Override
    public void save(Emp emp) {
        //1. 补齐参数
        //将123456使用md5之后设置为密码
        emp.setPassword(SecureUtil.md5("123456"));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());

        //2. 保存
        empMapper.save(emp);
    }

    @Override
    public Emp findById(Integer id) {
        return empMapper.findById(id);
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        empMapper.deleteByIds(ids);
    }

    @Override
    public void update(Emp emp) {
        //设置更新时间
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);
    }

    @Override
    public Emp login(LoginDTO loginDTO) {
        //1. 判度胺用户名和密码是否为空，如果为空就报错
        if (StrUtil.isEmpty(loginDTO.getUsername()) || StrUtil.isEmpty(loginDTO.getPassword())) {
            throw new BusinessException("用户名和密码不能为空");
        }
        //2.根据用户名查询，查询不到就报错
        Emp emp = empMapper.findByUserName(loginDTO.getUsername());
        if (emp == null) {
            throw new BusinessException("用户名不存在");
        }
        //3.将前端传入的明文密码加密后跟数据库中查询到的密码比对，查询不到就报错
        String pass = SecureUtil.md5(loginDTO.getPassword());
        if(!StrUtil.equals(pass,emp.getPassword())){
            throw new BusinessException("密码错误");
        }
        //4.上面都没有问题，返回查询到的员工对象
        return emp;
    }


//    @Override
//    public PageBean<Emp> findByPage(Integer page, Integer pageSize) {
//        //1. 查询记录总数
//        Long total = empMapper.findCount();
//
//        //2. 查询当前分页数据
//        Integer startIndex = (page - 1) * pageSize;
//        List<Emp> rows = empMapper.findList(startIndex, pageSize);
//        //3.组装返回数据
//        return new PageBean<Emp>(total,rows);
//
//    }


}

